package com.linln.admin.system.controller;

import com.linln.admin.system.service.AppService;
import com.linln.admin.system.validator.MenuValid;
import com.linln.common.constant.StatusConst;
import com.linln.common.data.QuerySpec;
import com.linln.common.enums.StatusEnum;
import com.linln.common.utils.*;
import com.linln.common.vo.ResultVo;
import com.linln.component.actionLog.action.SaveAction;
import com.linln.component.actionLog.action.StatusAction;
import com.linln.component.actionLog.annotation.ActionLog;
import com.linln.component.actionLog.annotation.EntityParam;
import com.linln.component.shiro.ShiroUtil;
import com.linln.component.thymeleaf.utility.DictUtil;
import com.linln.modules.system.domain.Menu;
import com.linln.modules.system.domain.Role;
import com.linln.modules.system.domain.User;
import com.linln.modules.system.repository.MenuRepository;
import com.linln.modules.system.repository.UserRepository;
import com.linln.modules.system.service.MenuService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;


@Controller
@RequestMapping("/system/menu")
public class MenuController {

    @Autowired
    private MenuService menuService;

    @Autowired
    private MenuRepository menuRepository;

    @Autowired
    private AppService appService;

    /**
     * 跳转到列表页面
     */
    @GetMapping("/index")
    @RequiresPermissions("system:menu:index")
    public ResponseEntity<?> index(Model model) {

        return appService.layTable(menuRepository, before -> {
                    // 返回模板参数
                    return model;
                },

                after -> {
                    // 列表查询条件
                    QuerySpec querySpec = QuerySpec.matching()
                            .withMatcher("title", QuerySpec.LIKE);
                    Specification<Menu> spec = QuerySpec.of(querySpec);
                    // 返回筛选条件
                    return spec;
                },

                "/system/menu/index",

                (pageResult) -> {
                    // 在这里处理 pageResult
                    // 例如：修改每一条数据
//                    pageResult.getContent().forEach(item -> {
//                        // 对每一项数据进行处理
//                    });
                }

        );

    }



    /**
     * 跳转到添加页面
     */
    @RequestMapping("/add")
    @RequiresPermissions("system:user:add")
    public ResponseEntity<?> add(Model model, @EntityParam Menu menu) throws Exception {

        return appService.form(menuRepository, "/system/menu/add", (isEdit) -> {

                    // 获取所有角色
                    List<Menu> menus = menuRepository.findAllByStatus(Sort.by(Sort.Order.asc("createDate")), (byte) 1);
                    model.addAttribute("menus", menus);

                    if (menu.getPid() != null) {
                        model.addAttribute("pid", menu.getPid());
                    }

                    return model;

                }, (data) -> {

                    // 保存前数据校验
                    List<ValidationUtil.ValidationRule<?>> rules = new ArrayList<>();

                    // 执行校验
                    return ValidationUtil.validateFields(rules);

                }, (data) -> {

                    // 数据处理
                    if (menu.getId() != null) { // 编辑
                        Menu beMenu = menuRepository.getById(menu.getId());
                        EntityBeanUtil.copyProperties(beMenu, menu, "sort"); // 将beMenu 字段复制到 menu
                    } else {
                        menu.setSort(0);
                    }

                    Menu pMenu = menuService.getById(menu.getPid());
                    menu.setPids(pMenu.getPids() + ",[" + menu.getPid() + "]");


                    return menu;

                },

                (data) -> {
                    // 保存后续逻辑在这写
                });
    }


    /**
     * 排序
     * @param model
     * @param menu
     * @return
     * @throws Exception
     */
    @RequestMapping("/sort")
    @RequiresPermissions("system:menu:sort")
    public ResponseEntity<?> sort(Model model, @EntityParam Menu menu) throws Exception {

        return appService.save(menuRepository, (data) -> {

            // 校验数据
            return ValidationUtil.validateFields(new ArrayList<>());

        }, (data) -> {

//            try {
//                throw new Exception("异常");
//            }

            // 处理数据
            Menu origin = menuRepository.getById(menu.getId());
            origin.setSort(menu.getSort());
            return origin;

        }, (data) -> {
            // 更新后操作
        });

    }

    /**
     * 删除菜单
     */
    @RequestMapping("/remove")
    @RequiresPermissions("system:menu:remove")
    public ResponseEntity<?> remove(@RequestParam(value = "id") Menu menu)
    {
        return appService.save(menuRepository, (data) -> {
            // 校验数据
            return ValidationUtil.validateFields(new ArrayList<>());
        }, (data) -> {
            menu.setStatus(StatusConst.DELETE);
            return menu;
        }, (data) -> {
            // 更新后操作
        });

    }


}
